package com.lzs.system.security;

import com.alibaba.fastjson.JSONObject;
import com.lzs.common.config.Constant;
import com.lzs.common.config.JwtTokenUtil;
import com.lzs.common.dao.SysMenuDao;
import com.lzs.common.dao.SysRoleDao;
import com.lzs.common.dao.UserAuthDao;
import com.lzs.common.exception.LzsBusinessException;
import com.lzs.common.service.UserAuthService;
import com.lzs.common.utils.SecurityUser;
import com.lzs.common.vo.CommonResult;
import com.lzs.common.vo.GetUserPowerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author kczhang@wisedu.com
 * @version 1.0.0
 * @since 2020-12-04
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final String JWT_PREFIX = "Bearer ";
    private static final String AUTHORIZATION_HEAD = "Authorization";

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserAuthDao userAuthDao;
    @Autowired
    private SysRoleDao sysRoleDao;
    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private UserAuthService userAuthService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String authorizationHead = request.getHeader(AUTHORIZATION_HEAD);
            if (authorizationHead != null && authorizationHead.startsWith(JWT_PREFIX)) {
                String token = authorizationHead.substring(JWT_PREFIX.length());
                String userId = null;
                    userId = JwtTokenUtil.getUserIdFromToken(token);

                GetUserPowerVo userPower = userAuthService.getUserPower(userId);
                String userName = userPower.getUserName();
                List<String> roleNameList = userPower.getRoleNameList();
                List<String> menuCodeList = userPower.getMenuCodeList();
                //用户角色权限
                List simpleGrantedAuthorityList = new ArrayList<SimpleGrantedAuthority>();
                for (String roleName : roleNameList) {
                    simpleGrantedAuthorityList.add(new SimpleGrantedAuthority(Constant.ROLE_+roleName));
                }
                for (String menuCode : menuCodeList) {
                    simpleGrantedAuthorityList.add(new SimpleGrantedAuthority(menuCode));
                }
                SecurityUser user = new SecurityUser(userId,userName,"",simpleGrantedAuthorityList);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, token,simpleGrantedAuthorityList);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }catch (LzsBusinessException e){
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            writer.print(JSONObject.toJSONString(CommonResult.Err(e.getCodeEnum(),e.getMessage())));
            writer.flush();
            writer.close();
            return;
        }
        filterChain.doFilter(request, response);
    }

}
